#!/bin/env python
# -*- coding: utf-8 -*-

"""
File Name: result_util.py
Author: morre <morre@vip.qq.com>
Create Time: 2022/12/31 17:03:16
Brief:
"""

from __future__ import absolute_import


class Row(dict):
    """Hbase行结构解析类"""
    def __init__(self, key=None, cells=None):
        """Row object.
        Args:
            key (str): Row key.
            cells (dict[str, bytes]): Cells, e.g., {"family:qualifier": b"data"}
        """
        super(Row, self).__init__(cells)
        self.key = key

    def __str__(self):
        return f"{self.key}\t{super(Row, self).__repr__()}"

    def __repr__(self):
        return f"{self.key}\t{super(Row, self).__repr__()}"


def cells_to_row(pb_cells, with_timestamp):
    if not pb_cells:
        return None

    if with_timestamp:
        return Row(pb_cells[0].row, {
            pb_cell.family + b":" + pb_cell.qualifier: {
                b"@value": pb_cell.value, b"@timestamp": pb_cell.timestamp}
            for pb_cell in pb_cells
        })
    return Row(pb_cells[0].row, {
        pb_cell.family + b":" + pb_cell.qualifier: pb_cell.value
        for pb_cell in pb_cells
    })


def cells_to_rows(pb_cells, with_timestamp):
    if not pb_cells:
        return None
    row_dict = {}
    for pb_cell in pb_cells:
        key = pb_cell.row
        column = pb_cell.family + b":" + pb_cell.qualifier
        value = pb_cell.value
        try:
            row = row_dict[key]
        except KeyError:
            row = Row(key)
            row_dict[key] = row
        if with_timestamp is True:
            row[column] = {b"@value": value, b"@timestamp": pb_cell.timestamp}
        else:
            row[column] = value
    return list(row_dict.values())
